"use strict";
var mqtt = require("mqtt");
const EventEmitter = require('events');

class IotDevice extends EventEmitter{
    constructor(serverAddress = "182.61.12.15:8883"){
        super();
        this.serverAddress = `mqtts://${serverAddress}`;
    }

    connect(){
        this.client = mqtt.connect(this.serverAddress, {
            rejectUnauthorized: false,
            username: 'test',
            password: '123456'
        })    

        var self = this;
        this.client.on("connect", function(){
            self.emit("online")
        })

        this.client.on("offline", function(){
            self.emit("offline")
        })

        this.client.on("error", function(err){
            self.emit("error", err)
        })
    }

    disconnect(){
        if(this.client!=null){
            this.client.end();
        }
    }
}

module.exports = IotDevice;